<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            margin-top: 10px;
            background-color: #bfd;
        }
    </style>
</head>

<body>
    <!-- 需求: 键盘按下时发送请求, 服务端返回请求 -->
    <div id="result"></div>

    <script>
        const res = document.getElementById('result');

        window.onkeydown =  (event) => {
            // 创建对象
            const xhr = new XMLHttpRequest();
            
            // 设置响应体数据类型, 自动转换JSON字符串
            xhr.responseType = 'json';

            // 初始化请求, 发送请求, 绑定事件
            xhr.open('GET', 'http://127.0.0.1:8000/json-server');
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // // 把服务器返回的字符串转换成对象(手动转换)
                        // let data = JSON.parse(xhr.response);

                        let data = xhr.response;
                        res.innerHTML = data.name;
                    }
                }
            }
        }
    </script>

</body>
